package com.example.quartzdemo.util.job;

import com.example.quartzdemo.entity.TaskLog;
import com.example.quartzdemo.service.TaskLogRepository;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

public class QuartzJobUtil {
    public static void executeWithLogging(JobExecutionContext ctx,
                                          ApplicationContext appCtx,
                                          TaskLogRepository logRepo) {
        JobDataMap d = ctx.getMergedJobDataMap();
        String taskId = d.getString("taskId");
        String className = d.getString("className");
        String methodName = d.getString("methodName");
        TaskLog log = new TaskLog();
        log.setTaskId(taskId);
        log.setClassName(className);
        log.setMethodName(methodName);
        log.setExecTime(LocalDateTime.now());
        try {
            Class<?> cls = Class.forName(className);
            Object bean = appCtx.getBean(cls);
            Method m = cls.getMethod(methodName);
            m.invoke(bean);
            log.setStatus("SUCCESS");
            log.setMessage("执行成功");
        } catch (Exception e) {
            log.setStatus("FAILED");
            log.setMessage(e.toString());
        }
        logRepo.save(log);
    }
}

